from rest_framework import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import gettext_lazy as _
from apps.sys.dict.models import DictData


class WritableRelatedField(serializers.RelatedField):
    default_error_messages = {
        "does_not_exist": _("Object with {source} does not exist."),
        "invalid": _("Invalid value."),
    }

    def get_queryset(self):
        return super().get_queryset()

    def to_internal_value(self, data):
        try:
            data = data.get("value", None) if isinstance(data, dict) else data
            if isinstance(self.parent, serializers.ManyRelatedField):
                self.source = self.parent.source
            field = getattr(self.root.Meta.model, self.source).field
            if self.root.Meta.model == field.remote_field.model:
                return field.model._meta.concrete_model.objects.get(id=data)
            return field.remote_field.model._meta.concrete_model.objects.get(id=data)
        except ObjectDoesNotExist:
            self.fail("does_not_exist", source=self.source)
        except (TypeError, ValueError):
            self.fail("invalid")


class BaseNameWritableRelatedField(WritableRelatedField):
    def to_representation(self, value):
        return {"value": str(value.id), "label": value.name}


class BaseCaseNameWritableRelatedField(WritableRelatedField):
    def to_representation(self, value):
        level_label = DictData.objects.get(type="tms_tc_level", value=value.level).label
        return {"value": str(value.id), "label": f"【{level_label}】 {value.name}"}


class UserNameWritableRelatedField(WritableRelatedField):
    def to_representation(self, value):
        return {
            "value": str(value.id),
            "label": value.name + "(" + value.username + ")",
        }


class IPNameWritableRelatedField(WritableRelatedField):
    def to_representation(self, value):
        return {"value": str(value.id), "label": value.name + "(" + value.address + ")"}
